#include "Renderer_PCH.h"
#include "FontRequest.h"

/*--------------------------------------------------------------------------*/

FontRequest::FontRequest(const std::string& path) :
	m_path(path)
{
	pugi::xml_document mfile;
	bool loadingResult = mfile.load_file(m_path.c_str());
	__Check(loadingResult);

	if (!loadingResult)
	{
		__Crash("Failed to open or parse file: %s", m_path.c_str());
		return;
	}

	/*--------------------------------------------------------------------------*/

	RFont* font = g_Renderer->GetRendererStorageMgr()->CreateFont(::GetFileName(m_path));
	__Check(font);

	pugi::xml_node font_node = mfile.child("font");

	pugi::xml_node common_node = font_node.child("common");
	int scalew = common_node.attribute("scaleW").as_int(1);
	int scaleh = common_node.attribute("scaleH").as_int(1);

	pugi::xml_node pages_node = font_node.child("pages");
	std::string texture = pages_node.child("page").attribute("file").as_string("");
	m_texturename = ::GetFileName(texture);

	g_Renderer->AddRequest(NULL, new TextureRequest(::GetFilePath(path) + texture));

	pugi::xml_node chars_node = font_node.child("chars");
	for (pugi::xml_node charr = chars_node.child("char"); charr; charr = charr.next_sibling("char"))
	{
		// <char id="32" x="110" y="22" width="3" height="1" xoffset="-1" yoffset="31" xadvance="8" page="0" chnl="15" />
		int id = charr.attribute("id").as_int(0);

		float x = charr.attribute("x").as_int(0);
		float y = charr.attribute("y").as_int(0);

		float h = charr.attribute("height").as_int(0);
		float w = charr.attribute("width").as_int(0);

		float xo = charr.attribute("xoffset").as_int(0);
		float yo = charr.attribute("yoffset").as_int(0);

		float xa = charr.attribute("xadvance").as_int(0);

		font->m_chars[id].m_xadvance = xa;

		font->m_chars[id].m_source.x = (x + 0.5f) / scalew;			// left
		font->m_chars[id].m_source.y = 1.0f - ((y + 0.5f + h) / scaleh);	// bottom
		font->m_chars[id].m_source.z = (x + 0.5f + w) / scalew;	// right
		font->m_chars[id].m_source.w = 1.0f - ((y + 0.5f) / scaleh);			// top

		font->m_chars[id].m_destination.x = xo;// / scalew;		// left
		font->m_chars[id].m_destination.y = (yo + h);// / scaleh;	// bottom
		font->m_chars[id].m_destination.z = (xo + w);// / scalew;	// right
		font->m_chars[id].m_destination.w = yo;// / scaleh;		// top
	}

	m_font = font;
}

/*--------------------------------------------------------------------------*/

FontRequest::~FontRequest()
{

}

/*--------------------------------------------------------------------------*/

void* FontRequest::DoRequest()
{
	RTexture* tex = g_Renderer->GetRendererStorageMgr()->GetTexture(m_texturename);

	m_font->m_texture = tex;

	return m_font;
}

/*--------------------------------------------------------------------------*/
